﻿/******************************************************************************
    myBoard is a port of MacOS X dashboard application for windows.
    Copyright (C) 2007,2008  by Yann ALET
    Email : yann.alet@gmail.com

    myBoard is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    myBoard is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using myBoard.Framework;
using System.Reflection;
using System.IO;
using System.Drawing.Text;

namespace myBoard.PostIt
{
    /// <summary>
    /// Interaction logic for PostIt.xaml
    /// </summary>
    public partial class PostIt : UserControl , IMagnet, IRequiresStorage, IFlip
    {
        private Storage _storage;
        private StreamWriter _sw;
        private Settings _settings;
        private CheckBox _selectedSample;

        public PostIt()
        {
            InitializeComponent();
            _frontFlipButton.Click += new RoutedEventHandler(_frontFlipButton_Click);
            _doneButton.Click += new RoutedEventHandler(_doneButton_Click);
            foreach (CheckBox paperSample in _paperSamplesContainer.Children)
            {
                paperSample.Checked += new RoutedEventHandler(paperSample_Checked);
                paperSample.Unchecked += new RoutedEventHandler(paperSample_Unchecked);
            }

            _fontSelector.SelectionChanged += new SelectionChangedEventHandler(_fontSelector_SelectionChanged);
            _sizeSelector.SelectionChanged += new SelectionChangedEventHandler(_sizeSelector_SelectionChanged);

            _postitShape.MouseDown += new MouseButtonEventHandler(_postitShape_MouseDown);
        }

        void _postitShape_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _tbx.Focus();
        }

        void _sizeSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _tbx.FontSize = Convert.ToDouble(((ListBoxItem)_sizeSelector.SelectedItem).Content);
        }

        void _fontSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _tbx.FontFamily = new FontFamily(_fontSelector.Text);
        }

        void paperSample_Unchecked(object sender, RoutedEventArgs e)
        {
            
        }

        void paperSample_Checked(object sender, RoutedEventArgs e)
        {
            foreach (CheckBox paperSample in _paperSamplesContainer.Children)
            {
                if (paperSample != (CheckBox)sender)
                    paperSample.IsChecked = false;
            }

            CheckBox selectedSample = sender as CheckBox;
            GradientStop start = ((LinearGradientBrush)((Border)VisualTreeHelper.GetChild(selectedSample, 0)).Background).GradientStops[0];
            GradientStop end = ((LinearGradientBrush)((Border)VisualTreeHelper.GetChild(selectedSample, 0)).Background).GradientStops[1];
            ((LinearGradientBrush)_postitShape.Fill).GradientStops[0] = start;
            ((LinearGradientBrush)_postitShape.Fill).GradientStops[1] = end;
            if(_settings!=null)
                _settings.SelectedSampleIndex = _paperSamplesContainer.Children.IndexOf(selectedSample);
            _selectedSample = selectedSample;
        }

        void _doneButton_Click(object sender, RoutedEventArgs e)
        {
            FlipRequested(MagnetSides.Front);
        }

        void _frontFlipButton_Click(object sender, RoutedEventArgs e)
        {
            if (_settings != null)
                ((CheckBox)_paperSamplesContainer.Children[_settings.SelectedSampleIndex]).IsChecked = true;
            else
            {
                if(_selectedSample==null)
                    ((CheckBox)_paperSamplesContainer.Children[0]).IsChecked = true;
            }

            FlipRequested(MagnetSides.Back);
        }

        #region IMagnet Members

        public string StoreID 
        {
            get
            { return "{375E92D9-03F5-4e04-A3A5-7F2F5E231647}"; }
        }

        public event OnFlipRequested FlipRequested;

        public Panel GetBackSide()
        {
            return _backSide;
        }

        public Panel GetFlipZone()
        {
            return _flipzone;
        }

        public Panel GetFrontSide()
        {
            return _frontSide;
        }

        public BitmapImage GetLogoBitmapImage()
        {
            return ResourcesAccess.GetBitmapImageFromResouce("myBoard.PostIt.logo.png");
        }

        public System.Drawing.Image GetLogoImage()
        {
            return ResourcesAccess.GetImageFromResouce("myBoard.PostIt.logo.png");
        }

        public BitmapImage GetThumbBitmapImage()
        {
            return ResourcesAccess.GetBitmapImageFromResouce("myBoard.PostIt.thumb.png");
        }

        public System.Drawing.Image GetThumbImage()
        {
            return ResourcesAccess.GetImageFromResouce("myBoard.PostIt.thumb.png");
        }

        public string MagnetName
        {
            get { return "Post-It"; }
        }

        #endregion

        #region IRequiresStorage Members

        public void GetStorage(Storage storage)
        {
            _storage = storage;
            FileInfo fi = new FileInfo(System.IO.Path.Combine(storage.StorageDirectory.FullName, "text.txt"));
            if (fi.Exists)
            {
                StreamReader sr = fi.OpenText();
                _tbx.Text = sr.ReadToEnd();
            }

            string settingsFullPath = System.IO.Path.Combine(_storage.StorageDirectory.FullName, "settings.xml");
            if (File.Exists(settingsFullPath))
            {
                _settings = Serialization.DeSerialize(settingsFullPath);
                System.Drawing.Color startDrawingColor = System.Drawing.ColorTranslator.FromHtml(_settings.StartColor);
                System.Drawing.Color endDrawingColor = System.Drawing.ColorTranslator.FromHtml(_settings.EndColor);

                ((LinearGradientBrush)_postitShape.Fill).GradientStops[0] = new GradientStop(Color.FromRgb(startDrawingColor.R, startDrawingColor.G, startDrawingColor.B), 0);
                ((LinearGradientBrush)_postitShape.Fill).GradientStops[1] = new GradientStop(Color.FromRgb(endDrawingColor.R, endDrawingColor.G, endDrawingColor.B), 1);

                _fontSelector.Text = _settings.FontFamily;

                foreach (ListBoxItem item in _sizeSelector.Items)
                    if (Convert.ToDouble(item.Content) == _settings.FontSize)
                    {
                        _sizeSelector.SelectedItem = item;
                        break;
                    }
            }
            else
            {
                _fontSelector.Text = _tbx.FontFamily.ToString();
                foreach (ListBoxItem item in _sizeSelector.Items)
                    if (Convert.ToDouble(item.Content) == _tbx.FontSize)
                    {
                        _sizeSelector.SelectedItem = item;
                        break;
                    }
            }
            

        }

        public void SaveState()
        {
            try
            {
                if (_storage != null)
                {
                    FileInfo textFI = new FileInfo(System.IO.Path.Combine(_storage.StorageDirectory.FullName, "text.txt"));
                    if (textFI.Exists)
                        textFI.Delete();
                    _sw = textFI.CreateText();
                    _sw.Write(_tbx.Text);
                    _sw.Close();

                    Color startColor = ((LinearGradientBrush)_postitShape.Fill).GradientStops[0].Color;
                    Color endColor = ((LinearGradientBrush)_postitShape.Fill).GradientStops[1].Color;

                    Settings settings = new Settings();
                    settings.StartColor = startColor.ToString();
                    settings.EndColor = endColor.ToString();
                    settings.FontFamily = _fontSelector.Text;
                    settings.FontSize = _tbx.FontSize;
                    foreach (CheckBox sample in _paperSamplesContainer.Children)
                        if ((bool)sample.IsChecked)
                        {
                            settings.SelectedSampleIndex = _paperSamplesContainer.Children.IndexOf(sample);
                            break;
                        }

                    Serialization.Serialize(settings, System.IO.Path.Combine(_storage.StorageDirectory.FullName, "settings.xml"));
                }
            }
            catch (Exception ex)
            {
                ExceptionsManager.LogException("PostIt", ex, false);
            }
        }

        #endregion

        #region IMagnet Members


        public void Terminate()
        {
            SaveState();
        }

        #endregion

        #region IMagnet Members


        public BitmapImage Icon
        {
            get
            {
                return ResourcesAccess.GetBitmapImageFromResouce("myBoard.PostIt.logo.png");
            }
        }

        BitmapImage _thumbnail;

        public BitmapImage Thumbnail
        {
            get
            {
                if (_thumbnail == null)
                {
                    _thumbnail = Tools.GetBitmapImageFromFrameworkElement(this);
                }
                return _thumbnail;
            }
        }

        #endregion
    }
}
